<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Silber\Bouncer\Database\Models;
use Bouncer;
use App\Http\Traits\UserPrivilege;
use App\Http\Requests\RoleRequest;

class RoleController extends Controller
{
    use UserPrivilege;
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $perPage = $request->input('pageSize',15);
        $name = $request->input('name', '');
        //Bouncer::scope()->onlyRelations();
        $query = Bouncer::Role()->query();
        if(!empty($name)) {
            $query->where('name', 'like', $name.'%');
        }
        $created = $request->input('created_at', []);
        if(!empty($created)) {
            $query->whereBetween('created_at', $created);
        }

        $roles = $query->paginate($perPage);

        return $this->success('', ['data'=>$roles]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(RoleRequest $request)
    {
        $data = $request->input();

        $ability = Bouncer::role()->create($data);
		
        if($ability){
            return $this->success('添加成功');
        }else{
            return $this->error('添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(RoleRequest $request, $id)
    {
        $data = $request->input();
        $ability = Bouncer::role()->findOrFail($id);
        if($ability->update($data)){
            return $this->success('保存成功');
        }else{
            return $this->error('保存失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ability = Bouncer::role()->findOrFail($id);
        $configRoles = config('auth.roles');
        if(in_array($ability->name, $configRoles)) {
            return $this->error('系统角色，禁止删除');
        }
        if(!$ability->delete()){
            return $this->error('删除失败');
        }
    }

    public function getRoleAbilities($role)
    {
        $user = $this->user();
        Bouncer::scope()->to(null);
        if($this->isSuper($user)){
            $allAbilities = Bouncer::ability()->select(['name','title'])->get()->toArray();
            $all = $this->formatAbility($allAbilities);
            $allTree = $this->formatAbilityTree($allAbilities);
        }else{
                   // $this->bouncer->scope()->onlyRelations();
          Bouncer::scope()->onlyRelations();
                    $all2=Bouncer::role()
                ->with('abilities')
                 ->get()
                ->map(function($item){
                    return $item['abilities'];
                })
                ->flatten()
                ->unique('id');
        
        $all = $this->formatAbility($all2);  
        $allTree = $this->formatAbilityTree($all2);
        }
        

        $roleAbility = $this->formatAbility($this->roleAbility($role));
 
        //$roleAbilityTree = $this->formatAbilityTree($this->roleAbility($role));

        return $this->success('', [ 'data'=>compact('all', 'roleAbility', 'allTree'), 'desc'=>config('ability')]);
    }

    protected function formatAbility($data) 
    {
        if(empty($data)){
            return [];
        }

        $result = [];
        foreach($data as $item) {
            $name = array_get($item, 'name');
            if($name == '*'){
                continue;
            }
            $group = substr($name, 0, strrpos($name,'.'));
            if(empty($group)){
                $group = $name;
            }
            // $name = str_replace($group.'_', '' , $item->name);array_get($item, 'title')
            $result[$group][]=['value'=>$name, 'label'=>array_get($item, 'title')];
        }
        return $result;

    }

    protected function formatAbilityTree($data) 
    {
        if(empty($data)){
            return [];
        }

        $result = [];
        foreach($data as $item) {
            $name = array_get($item, 'name');
            if($name == '*'){
                continue;
            }
            $group = substr($name, 0, strrpos($name,'.'));
            if(empty($group)){
                $group = $name;
            }
            if(!array_has($result, $group)) {
                $result[$group]=['value'=>$group.'.*', 'label'=>$group, 'children'=>[]];
            }
            $result[$group]['children'][]=['value'=>$name, 'label'=>array_get($item, 'title')];
        }
        return array_values($result);

    }
    
    protected function roleAbility($role) {
        $model = Bouncer::role()->where('name','=',$role)->first();
        $list = $model->getAbilities()->toArray();
        return $list;
    }
    
    public function saveRoleAbility(Request $request,$role) {
        $abilities = $request->input();
        $to = array_get($abilities, 'ability', []);
        Bouncer::scope()->dontScopeRoleAbilities();
        Bouncer::sync($role)->abilities($to);
        return $this->success('保存角色权限成功');
    }
}
